var foodDao = require('../../dao/foodDao.js');
var fs = require('fs');
var winston = require('../../utils/winstonLogger.js');

module.exports = {
    getFoodListByMerchantId : getFoodListByMerchantId,
    addFood : addFood,
    updateFood : updateFood,
    deleteFood : deleteFood
}

function getFoodListByMerchantId(req,res,next) {
    console.log(req.session.user);
    let merchantId = req.params.merchantId;
    foodDao.queryFood({merchant:merchantId},(err,result)=>{
        if(err){
            winston.error("query food error !");
        }else{
            res.json(result);
        }
    })
}

function addFood(req,res,next) {
    let body = req.body;
    console.log(body);
    let files = req.files;
    let localPath = 'D:/o2o/images';
    let remotePath = 'http://10.222.29.156:3456/images';
    let foodPath = '/food/' + body.name + '-' + Date.now() + '.jpg';
    console.log(foodPath);
    fs.writeFile(localPath + foodPath, files.image[0].buffer, function (err) {
        if (err)
            console.error(err);
    });
    let food = body;
    food.image = remotePath + foodPath;
    foodDao.addFood(food,(err,result)=>{
        if(err){
            winston.error("add food error !");
        }else{
            res.json(result);
        }
    })
}

function updateFood(req,res,next) {
    let body = req.body;
    let files = req.files;
    let localPath = 'D:/o2o/images';
    let remotePath = 'http://10.222.29.156:3456/images';
    let foodPath = '/food/' + body.name + '-' + Date.now() + '.jpg';
    console.log(body);
    fs.writeFile(localPath + foodPath, files.image[0].buffer, function (err) {
        if (err)
            console.error(err);
    });
    let newFood = body;
    newFood.image = remotePath + foodPath;
    foodDao.updateFood(newFood,(err,result)=>{
        if(err){
            console.log("update food error !");
        }else{
            res.json(result);
        }
    })
}

function deleteFood(req,res,next) {
    let foodId = req.params.foodId;
    foodDao.deleteFood(foodId,(err,result)=>{
        if(err){
            winston.error("delete food error !");
        }else{
            res.json(result);
        }
    })
}